/*
 * Copyright (C) 2005-2008 Alfresco Software Limited.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

 * As a special exception to the terms and conditions of version 2.0 of 
 * the GPL, you may redistribute this Program in connection with Free/Libre 
 * and Open Source Software ("FLOSS") applications as described in Alfresco's 
 * FLOSS exception.  You should have received a copy of the text describing 
 * the FLOSS exception, and it is also available here: 
 * http://www.alfresco.com/legal/licensing"
 */

package org.alfresco.extension.avmversions.webscripts;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.alfresco.extension.avmversions.AVMPurgeVersionsService;
import org.alfresco.web.scripts.DeclarativeWebScript;
import org.alfresco.web.scripts.Cache;
import org.alfresco.web.scripts.WebScriptException;
import org.alfresco.web.scripts.WebScriptRequest;
import org.alfresco.web.scripts.Status;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * ####TODO: Add description
 *
 * @author Peter Monks (peter.monks@alfresco.com)
 * @version $Id$
 */
public class AVMPurgeVersionsWebScript
    extends DeclarativeWebScript
{
    private final static Log log = LogFactory.getLog(AVMPurgeVersionsWebScript.class);
    
    private final static String PARAMETER_NAME_AVM_STORE      = "avmStore";
    private final static String PARAMETER_NAME_PURGE_TYPE     = "purgeType";
    private final static String PARAMETER_NAME_VERSION_NUMBER = "version";
    private final static String PARAMETER_NAME_DATE           = "isoDate";
    
    private final static String RESPONSE_PARAMETER_AVM_STORE            = PARAMETER_NAME_AVM_STORE;
    private final static String RESPONSE_PARAMETER_PURGED_VERSION_COUNT = "purgedVersionCount";

    private final static DateFormat ISO8601_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    private enum PurgeType
    {
        VERSION, DATE;
    };

    private final AVMPurgeVersionsService avmVersionPurgeService;
    
    
    public AVMPurgeVersionsWebScript(final AVMPurgeVersionsService avmVersionPurgeService)
    {
        // PRECONDITIONS
        assert avmVersionPurgeService != null : "avmVersionPurgeService must not be null.";
        
        // Body
        this.avmVersionPurgeService = avmVersionPurgeService;
    }


    /**
     * @see org.alfresco.web.scripts.DeclarativeWebScript#executeImpl(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptStatus, org.alfresco.web.scripts.WebScriptCache)
     */
    @Override
    protected Map<String, Object> executeImpl(final WebScriptRequest request, final Status status, final Cache cache)
    {
        Map<String, Object> result             = null;
        String              avmStore           = null;
        String              purgeTypeAsString  = null;
        PurgeType           purgeType          = null;
        int                 purgedVersionCount = 0;
        
        // PRECONDITIONS
        assert request != null : "request must not be null.";
        assert status  != null : "status must not be null.";
        assert cache   != null : "cache must not be null.";
        
        // Body
        
        // Retrieve and validate args
        avmStore          = request.getParameter(PARAMETER_NAME_AVM_STORE);
        purgeTypeAsString = request.getParameter(PARAMETER_NAME_PURGE_TYPE);
        
        if (avmStore == null || avmStore.trim().length() == 0)
        {
            throw new WebScriptException("Parameter " + PARAMETER_NAME_AVM_STORE + " is mandatory.");
        }
        
        if (purgeTypeAsString == null || purgeTypeAsString.trim().length() == 0)
        {
            throw new WebScriptException("Parameter " + PARAMETER_NAME_PURGE_TYPE + " is mandatory.");
        }
        
        // Determine purge type and call appropriate method
        purgeType = PurgeType.valueOf(purgeTypeAsString.toUpperCase());
        
        switch (purgeType)
        {
            case VERSION:
                purgedVersionCount = purgeByVersion(avmStore, request.getParameter(PARAMETER_NAME_VERSION_NUMBER));
                break;
                
            case DATE:
                purgedVersionCount = purgeByDate(avmStore, request.getParameter(PARAMETER_NAME_DATE));
                break;
        }
        
        // Build response object for FTL template
        result = new HashMap<String, Object>();
        result.put(RESPONSE_PARAMETER_AVM_STORE, avmStore);
        result.put(RESPONSE_PARAMETER_PURGED_VERSION_COUNT, purgedVersionCount);
        
        return(result);
    }
    
    
    private int purgeByVersion(final String avmStore, final String versionNumberAsString)
    {
        int result  = -1;
        int version = -1;
        
        version = Integer.valueOf(versionNumberAsString);

        result = avmVersionPurgeService.purgeAllBefore(avmStore, version);
        
        return(result);
    }
    
    private int purgeByDate(final String avmStore, final String dateAsString)
    {
        int  result    = -1;
        Date purgeDate = null;
        
        try
        {
            purgeDate = ISO8601_DATE_FORMAT.parse(dateAsString);
        }
        catch (ParseException pe)
        {
            throw new WebScriptException("Unable to parse date " + dateAsString + ".", pe);
        }
        
        result = avmVersionPurgeService.purgeAllBefore(avmStore, purgeDate);
        
        return(result);
    }

}
